
import { find, instantiate, Prefab, UITransform } from 'cc';
import { tyqSDK } from '../Managers/TyqSDK';
import { tyqConstants } from '../Constans/TyqConstants';
import { TyqBaseLayer } from '../UI/TyqBaseLayer';
import { tyqResManager } from '../Managers/TyqResManager';

class TyqLayerManager {

    private static _instance: TyqLayerManager;
    private constructor() {
    }
    public static get instance(): TyqLayerManager {
        if (this._instance == null) {
            this._instance = new TyqLayerManager();
        }

        return this._instance;
    }

    openLayer(layerName: string, obj?: any, cb?: Function) {
        let path = tyqConstants.paths.layer + layerName;
        tyqResManager.loadAsset(tyqConstants.bundles.tyqSDKBundle, path, Prefab, null, (err, prefab) => {
            if (err) {
                tyqSDK.log("LayerManager.openLayer error:" + err.message, layerName, err);
                return;
            }
            let node = instantiate(prefab);
            let com = node.addComponent(layerName);
            com.obj = obj;
            com.cb = cb;
            com.layerName = layerName;

            // 设置显示层级，保证在最上面
            node.getComponent(UITransform).priority = 999;
            node.parent = find("Canvas");

            tyqSDK.log("openLayer " + layerName, obj);
        });
    }

    closeLayer(layer: TyqBaseLayer) {
        let layerName = layer.layerName;
        layer.node.destroy();
    }

}

export const tyqLayerManager = TyqLayerManager.instance;
